import { HttpException, Injectable } from '@nestjs/common';
import { Repository, Like } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Film } from './entitise/film.entity';

@Injectable()
export class FilmsService {
  constructor(
    @InjectRepository(Film) private readonly film: Repository<Film>,
  ) {}

  async createFilm(req) {
    const { name } = req;
    if (!name) {
      throw new HttpException('缺少电影名称', 400);
    }
    const doc = await this.film.findOne({ where: { name } });
    if (doc) {
      throw new HttpException('电影已存在', 400);
    }
    await this.film.save(req);
    return null;
  }

  async getFilmList(req) {
    const { page = 1, pageSize = 5, ...res } = req;
    const qb = this.film.createQueryBuilder('film');
    const { name = '', ...rest } = res;
    qb.where([{ name: Like(`%${name}%`), ...rest }]);
    qb.orderBy('film.releaseTime', 'DESC');
    const total = await qb.getCount();
    qb.limit(pageSize);
    qb.offset(pageSize * (page - 1));

    const list = await qb.getMany();
    return { list, total };
  }

  //更新
  async updateFilm(req) {
    const { id, ...res } = req;
    const exist = await this.film
      .createQueryBuilder('film')
      .select('film')
      .where('film.id = :id', { id })
      .getOne();
    if (!exist) {
      throw new HttpException(`id为${id}的电影不存在`, 400);
    }
    const films = this.film.merge(res, req);
    return await this.film.save(films);
  }

  // 刪除文章
  async deleteFilm(req) {
    const { id } = req;
    const exist = await this.film.findOneBy(req);
    if (!exist) {
      throw new HttpException(`id为${id}的电影不存在`, 400);
    }
    await this.film.remove(exist);
    return null;
  }
}
